<?php

/**
 * This is the model class for table "video".
 *
 * The followings are the available columns in table 'video':
 * @property string $id
 * @property string $upload_src
 * @property string $upload_time
 * @property string $uid
 * @property string $pid
 * @property string $username
 */
class Video extends Base
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'video';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('upload_src', 'length', 'max'=>150),
			array('upload_time, uid, pid', 'length', 'max'=>10),
			array('username', 'length', 'max'=>20),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, upload_src, upload_time, uid, pid, username', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'upload_src' => '上传路径',
			'upload_time' => '上传时间',
			'uid' => '上传id',
			'pid' => '视频集',
			'username' => '上传人',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('upload_src',$this->upload_src,true);
		$criteria->compare('upload_time',$this->upload_time,true);
		$criteria->compare('uid',$this->uid,true);
		$criteria->compare('pid',$this->pid,true);
		$criteria->compare('username',$this->username,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Video the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public function upload() {
        //图片、视频，上传参数
        if (isset(Yii::app()->params['upload']['video'])) {
            $upload_params = Yii::app()->params['upload']['video'];
        } else {
            $upload_params = array(
                'size' => '1M',
                'allowExtensions' => array('mp4'),
                'directory' => 'upload'
            );
        }
        $video_dir = '/static/flash/' . date('Y-m-d') . '/';
        $upload_dir = Yii::getPathOfAlias('webroot') . $video_dir;
        try {
            $file = Yii::app()->file;
            $file->allowSize = $upload_params['size'];   //上传文件大小
            $file->allowExtensions = $upload_params['allowExtensions'];  //上传文件类型
            $file->setDirectory($upload_dir);  //设置文件上传目录
            $file->upload();
        } catch (CException $e) {
            $this->addError('upload', $e->getMessage());
            return false;
        }
        $this->upload_src = $video_dir . $file->getNameWithExtension();
        return true;
    }

    /**
     * 添加资源
     * @param $pid string 视屏集id
     * @return bool 添加是否成功
     */
    public function videoAdd($pid) {
        if (empty($this->upload_src)) {
            $this->addError('video', '未上传视屏');
            return false;
        }
        $this->title = Yii::app()->file->getOriginName();
        $this->upload_time = time();   //上传时间
        $this->uid = Yii::app()->session['auth']['id']; //上传人
        $this->username = Yii::app()->session['auth']['username'];
        $this->pid = $pid;
        return $this->save();
    }

    protected function pageListCondition(CDbCriteria $criteria) {
        $params = array();
        if (!empty($this->title)) {
            $criteria->addCondition('title like :title');
            $params[':title'] = $this->title . '%';
        }
        if (!empty($this->pid)) {
            $criteria->addCondition('pid=:pid');
            $params[':pid'] = $this->pid;
        }
        $criteria->params = $params;
    }
    /**
     * 删除图片
     * @return bool 删除成功/失败
     */
    public function remove() {
        $root_path = Yii::getPathOfAlias('webroot');  //网站根目录
        $upload_src = $root_path . $this->upload_src;

        if (!empty($this->upload_src) && file_exists($upload_src)) {
            $is_success = unlink($upload_src);
            if (!$is_success) {
                $this->addError('remove', '视频文件删除失败');
                return false;
            }
        }
        return $this->delete();
    }

}
